// pages/user/user.js
const app = getApp();
const request = require('../../utils/request');
const Toast = require('../../utils/toast');

Page({
  data: {
    userInfo: null,
    isLogin: false,
    isGuest: false,
    systemName: '',
    systemVersion: ''
  },

  onLoad() {
    this.loadUserInfo();
    this.loadSystemConfig();
  },

  onShow() {
    this.loadUserInfo();
  },

  // 加载系统配置
  loadSystemConfig() {
    const config = app.globalData.systemConfig || wx.getStorageSync('systemConfig');
    if (config) {
      this.setData({
        systemName: config.system_name,
        systemVersion: config.system_version
      });
    }
  },

  // 加载用户信息
  loadUserInfo() {
    const token = wx.getStorageSync('token');
    const userInfo = wx.getStorageSync('userInfo');

    if (token && userInfo) {
      this.setData({
        isLogin: true,
        userInfo: userInfo,
        isGuest: userInfo.isGuest || false
      });
    } else {
      this.setData({
        isLogin: false,
        userInfo: null
      });
    }
  },

  // 跳转到登录页
  goToLogin() {
    wx.navigateTo({
      url: '/pages/login/login'
    });
  },

  // 跳转到订单页面
  goToOrders() {
    const userInfo = wx.getStorageSync('userInfo');
    
    // 检查是否登录
    if (!this.data.isLogin || !userInfo) {
      Toast.error('请先登录');
      return;
    }

    // 检查是否是游客（游客不能查看订单）
    if (userInfo.isGuest === true || userInfo.isGuest === 1) {
      wx.showModal({
        title: '提示',
        content: '游客不能查看订单，请先登录账号或注册账号',
        confirmText: '去登录',
        success: (res) => {
          if (res.confirm) {
            wx.navigateTo({
              url: '/pages/login/login'
            });
          }
        }
      });
      return;
    }

    wx.navigateTo({
      url: '/pages/order/order'
    });
  },

  // 跳转到客服页面
  goToCustomerService() {
    wx.navigateTo({
      url: '/pages/customer-service/customer-service'
    });
  },

  // 退出登录
  logout() {
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          wx.removeStorageSync('token');
          wx.removeStorageSync('userInfo');
          app.globalData.userInfo = null;
          app.globalData.token = null;

          this.setData({
            isLogin: false,
            userInfo: null
          });

          Toast.success('已退出登录');
        }
      }
    });
  }
});

